<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-present http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\AskModel;
use cmf\controller\AdminBaseController;
use think\Db;

class AskController extends AdminBaseController
{


    private function checkasklist($id){
        return DB::name('ask_list')->where('id',$id)->find();
    }
    public function index()
    {
        $map    = [];
        $data   = $this->request->param();
        $listid =isset($data['listid']) && $data['listid'] ? $data['listid'] : '';
        if(!$this->checkasklist($listid)){
            $this->error('信息错误！');
        }
        if ($listid != '') {
            $map[] = ['listid', '=', $listid];
        }
        $list = DB::name('ask')->where($map)->order("list_order asc")->paginate(10, false, ['query' => input()]);
        $list->each(function ($v, $k) {
            return $v;
        });
        $page = $list->render();
        $this->assign("status", $data['status']);
        $this->assign("page", $page);
        $this->assign('list', $list);
        $this->assign('listid', $listid);

        return $this->fetch();
    }


    public function add()
    {
        $data   = $this->request->param();
        $listid = $data['listid'] ? $data['listid'] : '';

        $this->assign('listid', $listid);
        $this->assign('status', $data['status']);
        return $this->fetch();
    }


    public function addPost()
    {
        if ($this->request->isPost()) {

            $data = $this->request->param();
            $title = $data['title'];
            $count_option = $data['count_option'];
            $count_max = $data['count_max'];
            $count_min = $data['count_min'];
            $option = $data['option'];
            $listid = $data['listid'];

            if($title=='' || $count_option=='' || $count_max='' || $count_min==''){
                $this->error('请填写完整信息');
            }

            foreach($option as $k=>$v){
                if($v==''){
                    $this->error('请填写完整信息');
                }
            }

            $data['option_json'] = json_encode($data['option']);
            unset($data['option']);

            //处理多图
            $thumbs_json = [];
            foreach ($data as $k => $v) {
                if (strpos($k, 'thumb') === false) {
                    continue;
                }
                $kk = (int)(substr($k, 5));
                $thumbs_json[(string)$kk] = $v;
                unset($data[$k]);
            }

            $data['thumbs_json'] = json_encode((object)$thumbs_json);

            $result = DB::name('ask')->insert($data);

            if (!$result) {
                $this->error($result);
            }
            $this->success("添加成功！");
        }
    }

    public function edit()
    {

        $data = $this->request->param();

        $listid = $data['listid'];
        $id             = $this->request->param('id');
        $result          = DB::name('ask')->where('id',$id)->find();
        $result['option'] = json_decode($result['option_json'],true);
        $result['thumbs_json'] = json_decode($result['thumbs_json'], true);
        $this->assign('result', $result);
        $this->assign('listid', $listid);
        $this->assign('status', $data['status']);

        return $this->fetch();
    }

    public function editPost()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $title = $data['title'] ?? '';
            $count_max = $data['count_max'] ?? '';
            $count_min = $data['count_min'] ?? '';
            $option = $data['option'];

            if($title=='' || $count_max=='' || $count_min==''){
                $this->error('请填写完整信息');
            }

            foreach($option as $k=>$v){
                if($v==''){
                    $this->error('请填写完整信息');
                }
            }

            $askData = DB::name('ask')->where(['id'=>$data['id']])->find();
            $optionCount = count($option);
            if ($askData['count_option'] != $optionCount) {
                $data['count_option'] = $optionCount;
            }

            $data['option_json'] = json_encode($option);
            unset($data['option']);

            //处理多图
            $thumbs_json = [];
            foreach ($data as $k => $v) {
                if (strpos($k, 'thumb') === false) {
                    continue;
                }
                $kk = (int)(substr($k, 5));
                $thumbs_json[(string)$kk] = $v;
                unset($data[$k]);
            }

            $data['thumbs_json'] = json_encode((object)$thumbs_json);

            if (isset($data['option_key'])) {
                unset($data['option_key']);
            }

            $result = DB::name('ask')->where(['id'=>$data['id']])->update($data);

            if (!$result) {
                $this->error($result);
            }
            $this->success("编辑成功！");
        }
    }


    /**
     * 移除选项
     */
    public function moveanswer() {
        $data = $this->request->param(); //选项索引
        $index = $data['index'] ?? '';
        $id = $data['id'] ?? 0;
        if ($index === '' || !$id) {
            $this->error('参数错误');
        }

        $askData = db('ask')->where('id', $id)->find();
        $optionArr = json_decode($askData['option_json'], true);
        $thumbsArr = json_decode($askData['thumbs_json'], true);
        $count = $askData['count_option'];

        //删除对应索引的答案和图片
        $upArr = [];
        if (isset($optionArr[$index])) {
            //不保留索引
            array_splice($optionArr,$index,1);
            $upArr['option_json'] = json_encode($optionArr);
            $count--;
            $upArr['count_option'] = $count;
        }

        if (isset($thumbsArr[$index])) {
            array_splice($thumbsArr, $index, 1);
            $upArr['thumbs_json'] = json_encode((object)$thumbsArr);
        }

        $res = db('ask')->where('id', $id)->update($upArr);
        if ($res) {
            $this->success('删除成功');
        }
        $this->error('删除失败');
    }


    public function delete()
    {
        if ($this->request->isPost()) {
            $id             = $this->request->param('id', 0, 'intval');
            if(DB::name('ask')->where('id',$id)->delete()){
                $this->success("删除成功！");
            }

            $this->error('信息错误');
        }
    }

    public function listOrder()
    {
        $noticepageModel = new  AskModel();
        parent::listOrders($noticepageModel);
        $this->success("排序更新成功！");
    }
}
